package cn.enjoy.tool.juc;

import lombok.AllArgsConstructor;
import lombok.SneakyThrows;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 3个线程顺序打印ABC
 *
 * @author K
 * @date 2022-03-20 12:16
 */
public class OrderPrint {

    private volatile static String flag = "A";
    private static final Object lock = new Object();


    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        for (int i = 1; i <= 10; i++) {
            executorService.submit(new A(i));
            executorService.submit(new B(i + 1));
            executorService.submit(new C(i + 2));
        }
        executorService.shutdown();
    }

    @AllArgsConstructor
    static class A implements Runnable {
        private final int num;

        @SneakyThrows
        @Override
        public void run() {
            boolean exec = true;
            while (exec) {
                synchronized (lock) {
                    if (flag.equals("A")) {
                        System.out.println("A");
                        flag = "B";
                        exec = false;
                    }
                }
            }

        }
    }

    @AllArgsConstructor
    static class B implements Runnable {
        private final int num;

        @SneakyThrows
        @Override
        public void run() {
            boolean exec = true;
            while (exec) {
                synchronized (lock) {
                    if (flag.equals("B")) {
                        System.out.println("B");
                        flag = "C";
                        exec = false;
                    }
                }
            }
        }
    }

    @AllArgsConstructor
    static class C implements Runnable {
        private final int num;

        @SneakyThrows
        @Override
        public void run() {
            boolean exec = true;
            while (exec) {
                synchronized (lock) {
                    if (flag.equals("C")) {
                        System.out.println("C");
                        flag = "A";
                        exec = false;
                    }
                }
            }
        }
    }
}
